package com.glxy.controller;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebFilter("/*")
public class LoginFilter implements Filter {
    public void destroy() {
    }

    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        HttpServletRequest request = (HttpServletRequest) req;
//        request.setCharacterEncoding("utf8");
        String[] urls = {"login", "css", "js", "register"};
        String url = request.getRequestURI().toString();
        for(String u : urls) {
            if (url.contains(u)) {
                chain.doFilter(req, resp);
                return ;
            }
        }
        Object user = request.getSession().getAttribute("user");
        if(user == null) {
            resp.getWriter().print("noLogin");
            HttpServletResponse response = (HttpServletResponse) resp;
            response.sendRedirect("/BigHomeworkProject/html/login.html");
        } else {
            chain.doFilter(req, resp);
        }
    }

    public void init(FilterConfig config) throws ServletException {

    }

}
